import time

import requests
import json

from requests import request

from job.src.function.record_log import mylog


class DingRebot:
    def __init__(self, url=None, proxy_url=None):
        self.url_real = url
        self.proxy_url = proxy_url
        if self.proxy_url is not None:
            self.url = self.proxy_url
        else:
            self.url = self.url_real

    def post(self, message, name_list=[], isAtAll=False):
        hearder = {'Content-Type': 'application/json', 'Connection': 'close'}
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            },
            "at": {
                "atMobiles": name_list,
                "isAtAll": isAtAll
            },
            "url": self.url_real
        }
        res = ''
        for i in range(3):
            try:
                mylog.info(f'Send info: {message}')
                mylog.info(data)
                res = requests.post(self.url, data=json.dumps(data), headers=hearder)
                res = str(res.text)
                # print(type(res))
                mylog.info(f'Send successfully!')
                break
            except Exception as e:
                mylog.info(f'{e}')
                mylog.info("Connection refused by the server..")
                time.sleep(5)
                continue
        return res

    def post_form(self, data):
        res2 = requests.post(self.url, files=data)
        return res2


def requestPost(url, data=None, json=None, **kwargs):
    res = request('post', url, data=data, json=json, **kwargs)
    return res



if __name__ == '__main__':
    message = 'JIRA通知:M202109232331,M202109232328,M202109232327,M202109232324,M202109232321,M202109232319,M202109221614,M202109162237,M202109102341,M202109102339等修改单距离承诺日期还有3日，请尽快完成测试。尚未分配测试，请各责任人主动认领验证！'
    name_list = []  # ['13509840405']
    url_proxy = 'http://127.0.0.1:5009/send_info'
    url_248 = 'https://oapi.dingtalk.com/robot/send?access_token=4675a4912286a6a74112619d7efd0271630dc5ecf5e17bd38a2bc5e94d0c60db'
    a  =      'https://oapi.dingtalk.com/robot/send?access_token=4675a4912286a6a74112619d7efd0271630dc5ecf5e17bd38a2bc5e94d0c60db'
    res = DingRebot(url_248).post(message, name_list, isAtAll=True)
    print(res)
